package com.photoeditor.demo.ui.widget.image.frame;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;


public class PhotoFrameView extends ImageView {

    private Bitmap mSrcBitmap;
    private PaintFlagsDrawFilter mPain;

    public PhotoFrameView(Context context) {
        this(context, null);
    }

    public PhotoFrameView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        mPain = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
    }

    public PhotoFrameView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    public void setSrcImage(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            Bitmap bm = ((BitmapDrawable) drawable).getBitmap();
            if (mSrcBitmap == null || mSrcBitmap != bm) {
                mSrcBitmap = bm;
            }
        }
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }

    /**
     * ------合成相框------
     **/
    public Bitmap getDestBitmap(Drawable frameDrawable) {
        //复制一个drawable对象，保证不对原drawable进行修改
        Drawable drawable = frameDrawable.getConstantState().newDrawable();
        if (mSrcBitmap != null && !mSrcBitmap.isRecycled()) {
            Bitmap copySrcBitmap = mSrcBitmap.copy(Bitmap.Config.ARGB_8888, true);
            Canvas canvas = new Canvas(copySrcBitmap);
            drawable.setBounds(0, 0, mSrcBitmap.getWidth(),
                    mSrcBitmap.getHeight());
            drawable.draw(canvas);
            return copySrcBitmap;
        }
        return mSrcBitmap;
    }

    public void reset() {
        mSrcBitmap = null;
    }

    public void setInitBitMap(Context context, int trueW, int trueH) {
//        setBackgroundDrawable(context.getResources().getDrawable(R.drawable.frame_a));
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            setVisibility(GONE);
            return true;
        }
        if (action == MotionEvent.ACTION_UP) {
            setVisibility(VISIBLE);
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

    @Override
    public void draw(Canvas canvas) {
        canvas.setDrawFilter(mPain);
        super.draw(canvas);
    }
}
